﻿if (typeof Axis == "undefined") Axis = {};
if (typeof Axis.Admin == "undefined") Axis.Admin = {};
var checkListAuthorized;
Axis.Admin.MemberGift = {
    Init: function () {
        var thisObj = this;
        thisObj.Grid.Init();
        var cmaskdate = new CMaskDate();
        cmaskdate.Init($("input[role=datepicker]"));
        var cdropdown = new CDropDownCheckList({ width: 200 });
        cdropdown.Init("#ddlFilter");

        $("#ddlCategory option").each(function () {
            var text = $.RemoveHTMLTags($(this).text());
            $(this).text(text);
        });
        checkListAuthorized = new CDropDownCheckList({ width: 302, maxDropHeight: 110, firstItemChecksAll: true });
        checkListAuthorized.Init("#ddlCategory, [id$='ddlProvinceFilter'],[id$='ddlEducationFilter'],[id$='ddlClassFilter'],[id$='ddlMaritalStatusFilter'],[id$='ddlEducationFilter'],[id$='ddlJobFilter'],[id$='ddlTypeFilter'],[id$='ddlGenderFilter']");
        $("#FormFilter").hide();
        $("#FormEdit").hide();
        thisObj.Event();
        thisObj.GetMemberInfo();
    },
    GetGiftLotteryList: function () {
        var pData = { ProjectID: $("#ddlProjectList").val() };
        $.ajax({
            url: 'Service/MemberService2.asmx/GetGiftLotteryList',
            type: 'POST',
            data: JSON.stringify(pData),
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (pData, textStatus, jqXHR) {
                var data = eval("(" + pData.d + ")");
                var htmlOption = "";
                var htmlLottory = "";
                $.each(data, function (index, item) {
                    if (item.GroupID == "50")
                        htmlOption += $.string.Format("<option value='{0}'>{1}</option>", item.ID, item.Name);
                    else
                        htmlLottory += $.string.Format("<option value='{0}'>{1}</option>", item.ID, item.Name);
                });
                $("#ddlGift").html(htmlOption);
                $("#ddlGiftLottory").html(htmlLottory);
                $("body").removeClass('iMarkets-overlay-modal');
            },
            beforeSend: function (jqXHR, settings) {
                $("#ddlGiftLottory").html('');
                $("#ddlGift").html('');
                $("body").addClass('iMarkets-overlay-modal');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //  overlay.Hide();
                $("body").removeClass('iMarkets-overlay-modal');
            },
            complete: function (XMLHttpRequest, textStatus) {
                // overlay.Hide();
            }
        });

    },
    GetMemberInfo: function () {
        var pData = { ID: MemberID };
        $.ajax({
            url: 'Service/MemberService2.asmx/GetMemberInfo',
            type: 'POST',
            data: JSON.stringify(pData),
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (pData, textStatus, jqXHR) {
                var data = eval("(" + pData.d + ")");
                if (data.length > 0) {
                    $("#txtLoginName").val(data[0].Email);
                    $("#txtFullName").val(data[0].FirstName + " " + data[0].LastName);
                    $("#txtMark").val(data[0].Mark);
                    $("#txtIDCard").val(data[0].CMND);
                }
            },
            beforeSend: function (jqXHR, settings) {

            },
            error: function (jqXHR, textStatus, errorThrown) {
                //  overlay.Hide();
            },
            complete: function (XMLHttpRequest, textStatus) {
                // overlay.Hide();
            }
        });

    },
    Grid: {
        ID: "#GridContents",
        PagesID: "#GridPages",
        GridURL: "Service/UserService.ashx?Action=GET&Context=GroupUser",
        Instance: null,
        Init: function () {
            var thisObj = this;
            var options = {
                datatype: function () {
                    var pData = { ID: MemberID };
                    $.ajax({
                        url: 'Service/MemberService2.asmx/GetMemberGiftData',
                        type: 'POST',
                        data: JSON.stringify(pData),
                        cache: false,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (pData, textStatus, jqXHR) {
                            var data = eval("(" + pData.d + ")");
                            $("#GridContents").clearGridData(true)
                            $("#GridContents").addRowData('RowNumber', data);
                        },
                        beforeSend: function (jqXHR, settings) {

                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            //  overlay.Hide();
                        },
                        complete: function (XMLHttpRequest, textStatus) {
                            // overlay.Hide();
                        }
                    });
                },
                colNames: [
                   'RowNumber', 'ID', 'Tên Tặng', 'Loại Quà', 'Dự Án', '', 'Số lượng', 'Ghi Chú', 'Trạng Thái', 'StatusID', 'Đổi điểm', 'Đổi điểm', 'Ngày Nhận', 'Ngày Đổi Điểm', 'Action'
                ],
                colModel: [
                    { name: 'RowNumber', index: 'RowNumber', width: 1, hidden: true, frozen: true, key: true },
                    { name: 'MemberGiftID', index: 'MemberGiftID', width: 1, hidden: true, frozen: true },
                    { name: 'Name', index: 'FullName', width: 200, frozen: true },
                    { name: 'GroupName', index: 'LoginName', width: 170 },
                    { name: 'ProjectName', index: 'ProjectName', width: 150, align: 'center' },
                    { name: 'ProjectID', index: 'Email', width: 1, align: 'center', hidden: true },
                   { name: 'ReceiptQuantity', index: 'ReceiptQuantity', width: 60, frozen: true, align: 'center' },
                    { name: 'ReceiptNote', index: 'ReceiptNote', width: 200, frozen: true, align: 'center' },
                    { name: 'ReceiptString', index: 'ReceiptString', width: 80, align: 'center' },
                    { name: 'IsReceipt', index: 'IsReceipt ', width: 70, align: 'center', hidden: true },

                    { name: 'IsConvertFromMark', index: 'IsReceipt ', width: 10, align: 'center', hidden: true },
                    { name: 'ConvertFromMark', index: 'IsReceipt ', width: 70, align: 'center' },
                     {
                         name: 'ReceiptDateTime', index: 'DateOfBirth', width: 90, align: 'center', formatter: 'date'
                           , formatoptions: {
                               srcformat: "m/d/Y",
                               newformat: "d/m/Y"
                           }

                     },
                     {
                         name: 'ConvertFromMarkDateTime', index: 'DateOfBirth', width: 90, align: 'center', formatter: 'date', formatoptions: {
                             srcformat: "m/d/Y",
                             newformat: "d/m/Y"
                         }
                     },

                    { name: 'Action', index: 'Action', width: 55, align: 'center' }
                ],
                afterInsertRow: function (rowid, aData, addData) {
                    var action = $.string.Format("<img class='imgAction' src='../../Images/16x16/edit.png' onclick=\"ShowEdit('{0}')\" title='Sửa'/>", rowid);
                    $(thisObj.ID).jqGrid('setCell', rowid, 'Action', action);
                    var actionReceipt = $.string.Format("<img class='imgAction' src='../../Images/16x16/Store.png'  title='Chưa nhận'/>", rowid);
                    if (aData.IsReceipt == true)
                        actionReceipt = $.string.Format("<img class='imgAction' src='../../Images/16x16/Receipt.png'  title='Đã nhận'/>", rowid);
                    $(thisObj.ID).jqGrid('setCell', rowid, 'ReceiptString', actionReceipt);
                    var ConvertFromMark = "";
                    if (aData.IsConvertFromMark == true)
                        ConvertFromMark = $.string.Format("<img class='imgAction' src='../../Images/16x16/changemark.png'  title='Quà đổi điểm'/>", rowid);
                    $(thisObj.ID).jqGrid('setCell', rowid, 'ConvertFromMark', ConvertFromMark);

                    if (aData.ReceiptDateTime.toString().indexOf('01/01/0001') == 0) {
                        $(thisObj.ID).jqGrid('setCell', rowid, 'ReceiptDateTime', "---");
                    }
                    if (aData.ConvertFromMarkDateTime.toString().indexOf('01/01/0001') == 0) {
                        $(thisObj.ID).jqGrid('setCell', rowid, 'ConvertFromMarkDateTime', "---");
                    }

                },
                onCellSelect: function (rowid, iCol, cellcontent, e) {
                },
                onSelectRow: function (rowid, status, e) {
                },
                ondblClickRow: function (rowid, iRow, iCol, e) {
                },
                height: 'auto',
                rownumbers: true,
                autowidth: true,
                shrinkToFit: false,
                rowNum: 10,
                pager: thisObj.PagesID
            };
            thisObj.Instance = new CGrid(options);
            thisObj.Instance.Init(thisObj.ID);
            thisObj.Instance.NavGrid();
            thisObj.Instance.FrozenColumns();
        },
        Reload: function () {
            var thisObj = this;
            if (thisObj.Instance)
                thisObj.Instance.ReloadGrid();
        },
        SelectRow: function () {
            var thisObj = this;
            if (thisObj.Instance) {
                return thisObj.Instance.SelectRow();
            }
            return null;
        }
    },
    DialogEdit: {
        ID: "#FormEdit",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            Axis.Admin.MemberGift.ClearForm();

            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Edit User",
                    width: 440,
                    height: 400
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            var buttonText = "";
            switch (action) {
                case "INSERT":
                    thisObj.Dialog.SetTitle("Thêm quà tặng");
                    $(thisObj.ID).find("[data-role='INSERT']").show();
                    $(thisObj.ID).find("#txtLoginName").focus();
                    buttonText = "Add";
                    $("#chk_ResetPassword").css("visibility", "hidden");
                    $("#txtPassword").removeAttr("readonly").removeAttr("no-data");
                    $("#txtLoginName,#txtPassword,#txtEmail,#txtUserFullName,#chk_SuperAdmin").parent().show();
                    $("#ddlCategory,#Admin_Menu").parent().hide();
                    $("#txtLoginName,#txtPassword").removeAttr("readonly", "readonly");
                    break;
                case "UPDATE":
                    thisObj.Dialog.SetTitle("Edit: " + opts.LoginName);
                    if (opts) {
                        $.each(opts, function (key, value) {
                            $(thisObj.ID).find("[data-field=" + key + "]").val(value);
                        });
                        $("#cbkIsReceipt").removeAttr("checked");
                        if (opts.IsReceipt == "true") {
                            $("#cbkIsReceipt").attr("checked", "checked");
                        }


                    }
                    buttonText = "Update";
                    thisObj.SetTitle("Cập nhật thông tin");

                    break;

            }
            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                                Axis.Admin.MemberGift.Update(action, opts);

                            }
                        },
                        {
                            text: "Cancel",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },
        SetTitle: function (title) {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.SetTitle(title);
            }
        }
    },
    DialogFilter: {
        ID: "#FormFilter",
        Dialog: null,
        Init: function (type, opts) {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Filter",
                    width: 330,
                    height: 400,
                    buttons: [
                        {
                            text: "Search",
                            click: function (e) {
                                var data = {};
                                $("#FormFilter").find("input,select").each(function () {
                                    var $this = $(this);
                                    if ($this.attr("data-field")) {
                                        var key = $this.attr("data-field");
                                        var value = $this.val();
                                        if ($.isArray(value)) {
                                            data[key] = value.join(", ");
                                        }
                                        else {
                                            data[key] = value;
                                        }
                                    }
                                });
                                data = decodeURIComponent($.param(data));
                                $("#GridContents").jqGrid('setGridParam', { url: "Service/UserService.ashx?Action=GET&" + data, page: 1 }).trigger("reloadGrid");
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Cancel",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

                    ]
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        }
    },
    ClearForm: function () {
        $("#FormEdit").find("[data-field]").each(function () {
            var $this = $(this);
            $this.val("");
            if ($this.is("select")) {
                var value = $this.find("option[Default-Value='1']").attr("value");
                $this.val(value);
            }

        });
        $("#chk_SuperAdmin").removeAttr("checked");
        $("#txtPassword").attr({
            "readonly": "readonly",
            "no-data": "1"
        });
        $("#chk_ResetPassword").removeAttr("checked");
        $("#FormEdit [data-role='INSERT']").hide();
        $("#ddlCategory option").removeAttr("selected");
        if (checkListAuthorized)
            checkListAuthorized.Refresh();
        $('.Menu_Tree').tree('uncheckAll');
    },

    AddGiftLottory: function (type, opts) {
        var data = {};
        $("#AddGift").find("input,select").each(function () {
            var $this = $(this);
            if ($this.attr("data-field") && $this.attr("no-data") != "1") {
                var key = $this.attr("data-field");
                data[key] = $this.val();
                if ($this.attr("role") == "datepicker") {
                    data[key] = $.CFormat.FormatDate($this.val(), "yyyy/MM/dd HH:mm", "vi-VN", "en-US");
                }
            }
        });
        /*     data.IsReceipt = $("#cbkIsReceipt").is(":checked") ? 1 : 0;
        data.ReceiptNote = $("#txtReceiptNote").val();
        */
        data.ActionMemberID = MemberID;

        $.ajax({
            url: 'Service/MemberService2.asmx/UpdateGiftLottory',
            type: 'POST',
            data: JSON.stringify(data),
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (pData, textStatus, jqXHR) {
                var data = eval("(" + pData.d + ")");
                if (data.IsSuccessfull) {
                    thisObj.Grid.Reload();
                    thisObj.DialogEdit.Close();
                }
                // else {
                $.CAlert.Alert({
                    Title: "Thông báo",
                    Content: data.Description
                });
                //}
                // $("#GridContents").addRowData('RowNumber', data);
            },
            beforeSend: function (jqXHR, settings) {

            },
            error: function (jqXHR, textStatus, errorThrown) {
                //  overlay.Hide();
            },
            complete: function (XMLHttpRequest, textStatus) {
                // overlay.Hide();
            }
        });
    },
    Update: function (type, opts) {
        var thisObj = this;
        var data = {};
        switch (type) {
            case "INSERT":
                $("#FormEdit").find("input,select").each(function () {
                    var $this = $(this);
                    if ($this.attr("data-field")) {
                        var key = $this.attr("data-field");
                        data[key] = $this.val();
                        if ($this.attr("role") == "datepicker") {
                            data[key] = $.CFormat.FormatDate(value, "yyyy/MM/dd HH:mm", "vi-VN", "en-US");
                        }

                    }
                });
                break;
            case "UPDATE":
                $("#FormEdit").find("input,select").each(function () {
                    var $this = $(this);
                    if ($this.attr("data-field") && $this.attr("data-role") != "INSERT" && $this.attr("no-data") != "1") {
                        var key = $this.attr("data-field");
                        data[key] = $this.val();
                    }
                });
                data.IsReceipt = $("#cbkIsReceipt").is(":checked") ? 1 : 0;
                data.ReceiptNote = $("#txtReceiptNote").val();
                data.ActionMemberID = MemberID;
                break;

            case "DELETE":
                data.ID = opts.ID;
                break;
        }
        data.Action = type;
        $.ajax({
            url: 'Service/MemberService2.asmx/UpdateGiftData',
            type: 'POST',
            data: JSON.stringify(data),
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (pData, textStatus, jqXHR) {
                var data = eval("(" + pData.d + ")");
                if (data.IsSuccessfull) {
                    thisObj.Grid.Reload();
                    thisObj.DialogEdit.Close();
                }

                $.CAlert.Alert({
                    Title: "Thông báo",
                    Content: data.Description
                });

                // $("#GridContents").addRowData('RowNumber', data);
            },
            beforeSend: function (jqXHR, settings) {

            },
            error: function (jqXHR, textStatus, errorThrown) {
                //  overlay.Hide();
            },
            complete: function (XMLHttpRequest, textStatus) {
                // overlay.Hide();
            }
        });

        /*
        $.Ajax({
        url: 'Service/UserService.ashx',
        type: 'POST',
        data: data,
        success: function (data, textStatus, jqXHR) {
        if (data) {
        data = eval("(" + data + ")");
        if (data.IsSuccessfull) {
        thisObj.Grid.Reload();
        thisObj.DialogEdit.Close();
        }

        $.CAlert.Alert({
        Title: "Thông báo",
        Content: data.Description
        });
        }
        },
        beforeSend: function (jqXHR, settings) {
        },
        error: function (jqXHR, textStatus, errorThrown) {
        },
        complete: function (XMLHttpRequest, textStatus) {
        }
        });
        */
    },
    Event: function () {
        var thisObj = this;
        $("#imgUserAdd").click(function () {
            thisObj.DialogAddGift.Init("INSERT");
        });
        $("#imgUserEdit").click(function () {
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID)
                thisObj.DialogEdit.Init("UPDATE", rowData);
            else {
                $.CAlert.Alert({
                    Title: "Cập nhật trạng thái",
                    Content: "Vui lòng chọn tài khoản cần sửa."
                });
            }
        });
        $("#imgUserDel").click(function () {
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID) {
                $.CAlert.Confirm({
                    Title: "Xóa tài khoản",
                    Content: $.string.Format("Bạn có chắc muốn xóa tài khoản [{0}].", rowData.Email)
                }, function (isOK) {
                    if (isOK)
                        thisObj.Update("DELETE", rowData);
                });
            }
            else {
                $.CAlert.Alert({
                    Title: "Xóa tài khoản",
                    Content: "Vui lòng chọn tài khoản cần xóa."
                });
            }

        });
        $("#imgUserFilter").click(function () {
            thisObj.DialogFilter.Init();
        });
        $("#ddlProjectList").change(function () {
            thisObj.GetGiftLotteryList();
        });
    },
    Validate: function () {

    },
    GetAdminCategory: function () {
        var data = {
            Action: "GetAdminCategory",
            FunctionCode: "AdminCategory",
            Context: "GroupUser"
        };
        $.Ajax({
            url: 'Service/UserService.ashx',
            type: 'POST',
            data: data,
            success: function (data, textStatus, jqXHR) {
                if (data) {
                    data = eval("(" + data + ")");
                    var ret_parent = "";
                    $.each(data, function (index, item) {
                        if (item.ParentID == 0)
                            ret_parent += $.string.Format('<li menuid="{0}"><input type="checkbox" value="{0}" code="{1}" id="menu_{0}" /><label for="menu_{0}">{2}</label></li>', item.ID, item.Code, $.RemoveHTMLTags(item.Name));
                    });

                    $(".Menu_Tree_Items").html(ret_parent);
                    $.each(data, function (index, item) {
                        var ret_child = "";
                        if (item.ParentID != 0) {
                            ret_child += $.string.Format('<li menuid="{0}"><input type="checkbox" value="{0}" code="{1}" id="submenu_{0}" /><label for="submenu_{0}">{2}</label></li>', item.ID, item.Code, $.RemoveHTMLTags(item.Name));
                            var $parent = $(".Menu_Tree_Items li[menuid='" + item.ParentID + "']");
                            if ($parent.length) {
                                if ($parent.find("ul").length == 0) {
                                    $parent.append("<ul></ul>");
                                }
                                $(".Menu_Tree_Items li[menuid='" + item.ParentID + "'] ul").append(ret_child);
                            }
                        }

                    });
                    $('.Menu_Tree').tree();
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    DialogAddGift: {
        ID: "#AddGift",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            Axis.Admin.MemberGift.ClearForm();

            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Edit User",
                    width: 440,
                    height: 400
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            var buttonText = "";
            switch (action) {
                case "INSERT":
                    thisObj.Dialog.SetTitle("Thêm quà tặng");
                    $(thisObj.ID).find("[data-role='INSERT']").show();

                    buttonText = "Add";

                    break;

            }
            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                                Axis.Admin.MemberGift.AddGiftLottory(action, opts);

                            }
                        },
                        {
                            text: "Cancel",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },
        SetTitle: function (title) {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.SetTitle(title);
            }
        }
    }
};
$(function () {
    Axis.Admin.MemberGift.Init();
    Axis.Admin.MemberGift.GetAdminCategory();


});
function ShowEdit(rowID) {
    var thisObj = Axis.Admin.MemberGift;
    var rowData = $(thisObj.Grid.ID).jqGrid('getRowData', rowID);
    if (rowData && rowData.MemberGiftID)
        thisObj.DialogEdit.Init("UPDATE", rowData);
}

function ShowDelete(rowID) {
    var thisObj = Axis.Admin.MemberGift;
    if (rowID) {
        var rowData = $(thisObj.Grid.ID).jqGrid('getRowData', rowID);
        $.CAlert.Confirm({
            Title: "Xóa tài khoản",
            Content: $.string.Format("Bạn có chắc muốn xóa tài khoản: [{0}].", rowData.LoginName)
        }, function (isOK) {
            if (isOK)
                thisObj.Update("DELETE", { ID: rowID });
        });
    }
    else {
        $.CAlert.Alert({
            Title: "Xóa bài viết",
            Content: "Vui lòng chọn bài viết cần xóa."
        });
    }

}


